<template>
  <view class="container">
    <!-- 主体内容区域 -->
    <view class="content">
      <view v-if="activeTab === 'recognize'">
        <!-- 智慧识图页面内容 -->
        <view class="title">{{ hello }}</view>
        <view class="image-container">
          <image :src="imageSrc" mode="aspectFit" class="uploaded-image"></image>
        </view>
        <view class="button-group">
          <button class="action-button" @click="uploadImage">上传图片</button>
          <button class="action-button" @click="recognizeImage">识别图片</button>
        </view>
        <textarea v-if="result" class="result-textarea" v-model="result" readonly></textarea>
        <button class="action-button" @click="goToHistory">历史记录</button>
	  </view>

	<view v-if="activeTab === 'chat'">
	  <!-- 聊天页面内容 -->
	  <view class="chat">
	    <view class="chat-box">
	      <view v-for="(message, index) in messages" :key="index" class="chat-message">
	        <view class="sender-label">{{ message.sender }}</view>
	        <view class="chat-message-text">{{ message.text }}</view>
	      </view>
	    </view>
	    
	    <!-- 输入框和发送按钮放同一行 -->
	    <view class="input-group">
	      <input type="text" v-model="userMessage" placeholder="请输入消息" class="chat-input" />
	      <button @click="sendMessage" class="send-button">发送</button>
	    </view>
	  </view>
	</view>

    </view>

    <!-- 改进后的底部导航栏 -->
    <view class="navbar">
      <button @click="setActiveTab('recognize')" :class="{'active': activeTab === 'recognize'}">
        <view class="navbar-icon">🔍</view>
      </button>
      <button @click="setActiveTab('chat')" :class="{'active': activeTab === 'chat'}">
        <view class="navbar-icon">💬</view>
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      hello: '智图慧影',
      imageSrc: '../../static/c1.png',
      fileName: '',  // 存储上传后的文件名
      result: '',     // 存储识别结果
      activeTab: 'recognize',  // 当前选中的 tab，默认为智慧识图
      userMessage: '',  // 用户消息
      aiResponse: '',   // AI 回复
      messages: []      // 消息列表
    };
  },
  methods: {
    // 上传图片
    uploadImage() {
      uni.chooseImage({
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          this.imageSrc = tempFilePaths[0];
          uni.uploadFile({
            url: 'http://127.0.0.1:8080/api/image/upload',
            filePath: tempFilePaths[0],
            name: 'file',
            success: (res) => {
              const data = JSON.parse(res.data);
              if (data.status === "success") {
                this.fileName = data.fileName;  // 获取文件名
              } else {
                console.error("上传失败:", data.message);
              }
            },
            fail: (err) => {
              console.error("上传失败:", err);
            }
          });
        }
      });
    },
    // 识别图片
    recognizeImage() {
      uni.request({
        url: `http://127.0.0.1:8080/api/image/recognize?fileName=${this.fileName}`,
        method: 'GET',
        success: (res) => {
          const keywords = res.data.result.join('\n');
          this.result = keywords;
        },
        fail: (e) => {
          console.log(e);
        }
      });
    },
	 goToHistory() {
	      uni.navigateTo({
	        url: '/pages/History/History'  // 跳转到 History 页面
	      });
	    },
	
    // 发送聊天消息
     sendMessage() {
          if (!this.userMessage.trim()) {
            return;
          }
    
          const message = this.userMessage.trim();
          this.userMessage = '';  // 清空输入框
    
          // 添加用户消息到消息列表
          this.messages.push({ sender: '我', text: message });
    
          // 添加正在思考的消息
          this.messages.push({ sender: 'AI', text: '正在思考...' });
    
          uni.request({
            url: 'http://127.0.0.1:8080/chat/send', // 后端聊天 API
            method: 'POST',
            data: { query: message }, // 发送数据
            header: {
              'Content-Type': 'application/x-www-form-urlencoded' // 明确设置为表单提交格式
            },
            success: (res) => {
              // 更新 AI 消息为实际回复内容
              const aiMessage = res.data.answer;
              this.aiResponse = aiMessage;  // 更新 aiResponse
    
              // 更新消息列表，替换"正在思考..."为 AI 的回复
              this.messages[this.messages.length - 1] = { sender: 'AI', text: aiMessage };
            },
            fail: (err) => {
              console.error('聊天请求失败:', err);
              this.aiResponse = '无法获取回复，请稍后再试。';
    
              // 失败时，将 AI 的回复添加到消息列表
              this.messages[this.messages.length - 1] = { sender: 'AI', text: '无法获取回复，请稍后再试。' };
            }
          });
        },
    // 切换选中的 tab
    setActiveTab(tab) {
      this.activeTab = tab;
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
  font-size: 14px;
  line-height: 24px;
  text-align: center;
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  align-items: center; /* 水平居中 */
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.image-container {
  width: 80%; /* 控制图片容器的宽度 */
  height: 150px; /* 控制图片容器的高度 */
  margin-bottom: 20px;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center; /* 垂直居中对齐图片 */
  justify-content: center; /* 水平居中对齐图片 */
  background-color: #fff;
}

.uploaded-image {
  max-width: 100%; /* 让图片自适应容器的宽度 */
  max-height: 100%; /* 让图片自适应容器的高度 */
}

.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.action-button {
  flex: 1;
  padding: 10px;
  font-size: 16px;
  color: #fff;
  background-color: #007aff;
  border: none;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-button:hover {
  background-color: #005bb5;
}

.result-textarea {
  width: 80%;
  height: 100px;
  padding: 10px;
  border: 1px solid #007aff;
  border-radius: 5px;
  background-color: #e6f7ff;
  color: #333;
  font-size: 14px;
  resize: none;
}



/* 改进后的底部导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-around;
  background: linear-gradient(to right, #6a11cb, #2575fc);
  padding: 10px 0;
  width: 100%;  /* 使宽度与手机屏幕一致 */
  height: 10%;
  position: fixed;  /* 固定在页面底部 */
  bottom: 0;  /* 紧贴底部 */
  left: 0;  /* 距离左侧 0px */
  z-index: 999;  /* 确保导航栏在所有内容之上 */
  box-shadow: 0px -4px 10px rgba(0, 0, 0, 0.1);
}

.navbar button {
  color: white;
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 10px;
}

.navbar button.active {
  font-weight: bold;
  border-bottom: 3px solid white;
}

.navbar button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.navbar-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.navbar-label {
  font-size: 14px;
}

/* 聊天样式 */
.chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-height: 80vh;
  width: 80%;
  margin: 0 auto;
}

.chat-box {
  width: 100%;
  height: 300px; /* 固定聊天框高度 */
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-sizing: border-box;
}

.chat-message {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
  max-width: 90%;
  word-wrap: break-word;
  background-color: #f1f1f1;
  position: relative;
}

.chat-message .sender-label {
  font-size: 12px;
  font-weight: bold;
  position: absolute;
  top: 5px;
  right: 10px;
  color: #888;
}

.chat-message-text {
  padding-top: 20px;
  font-size: 14px;
  color: #333;
}

/* 输入框和发送按钮容器：放同一行 */
.input-group {
  display: flex;
  justify-content: space-between; /* 在同一行中分配空间 */
  width: 100%;
  gap: 10px; /* 输入框和按钮之间的间隙 */
}

.chat-input {
  flex: 1; /* 输入框占满剩余空间 */
  padding: 10px;
  font-size: 16px;
  border: 1px solid #007aff;
  border-radius: 5px;
}

.send-button {
  padding: 5px;
  font-size: 14px;
  color: white;
  background-color: #007aff;
  border: none;
  border-radius: 5px;
  width: 100px; /* 固定按钮宽度 */
  height: 45px;
}

.send-button:hover {
  background-color: #005bb5;
}

.chat-response {
  margin-top: 20px;
  padding: 10px;
  background-color: #f0f0f0;
  color: #333;
  font-size: 14px;
  border-radius: 5px;
  text-align: center;
}


</style>
